package com.mzwise.tunnel.service;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.mzwise.tunnel.wx.pay.dto.UnifiedTradeRequest;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付相关工具
 */
public class WxTransferService {

    public WxTransferService(Configs configs) {
        if (configs.getWxTransferConfig() != null) {
            try {
                this.wxpay = new WXPay(configs.getWxTransferConfig(), WXPayConstants.SignType.MD5);
                System.out.println("tunnel:微信企业付款通道开启");
            } catch (Exception e) {
                System.out.println("tunnel:微信企业付款通道开启错误");
                e.printStackTrace();
            }
        }
    }

    private WXPay wxpay;

    /**
     * 正常金额转微信金额*100
     * @param amount
     * @return
     */
    public String amountToFee(BigDecimal amount) {
        return amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP).toString();
    }

    /**
     * 企业付款
     * @param partner_trade_no
     * @param openid
     * @param amount
     * @param desc
     * @return
     * @throws Exception
     */
    public Map<String, String> transfer(String partner_trade_no, String openid, BigDecimal amount, String desc) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        data.put("partner_trade_no", partner_trade_no);
        data.put("openid", openid);
        data.put("amount", amountToFee(amount));
        data.put("check_name", "NO_CHECK");
        data.put("desc", desc);
        try {
            Map<String, String> resp = wxpay.transfer(data);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
